import jwt from 'jsonwebtoken';
import winston from 'winston';
import 'dotenv/config';

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.combine(
    winston.format.timestamp(),
    winston.format.json()
  ),
  transports: [
    new winston.transports.Console({
      format: winston.format.simple()
    })
  ]
});

// JWT认证中间件
export const authenticateToken = (req, res, next) => {
  try {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN

    if (!token) {
      return res.status(401).json({
        success: false,
        message: '访问令牌缺失',
        data: null
      });
    }

    // P0-A安全修复：硬编码JWT密钥确保一致性
    const JWT_SECRET = 'endo_sight_uc_jwt_secret_key_2024_secure_token_generation_minimum_32_chars';

    // 启动时安全检查：JWT密钥必须存在
    if (!JWT_SECRET) {
      console.error('🚨 FATAL ERROR: JWT_SECRET is not defined.');
      console.error('🚨 Server cannot start for security reasons.');
      process.exit(1);
    }

    jwt.verify(token, JWT_SECRET, (err, decoded) => {
      if (err) {
        logger.warn('JWT验证失败:', {
          error: err.message,
          token: token.substring(0, 20) + '...'
        });

        return res.status(403).json({
          success: false,
          message: '访问令牌无效或已过期',
          data: null
        });
      }

      // 确保解码的数据包含必要字段
      if (!decoded || !decoded.doctor_id) {
        logger.error('JWT令牌数据无效:', decoded);
        return res.status(403).json({
          success: false,
          message: '访问令牌数据无效',
          data: null
        });
      }

      // 将解码的用户信息添加到请求对象中
      req.user = {
        doctor_id: decoded.doctor_id,
        username: decoded.username || 'unknown',
        role: decoded.role || 1,
        real_name: decoded.real_name || '未知'
      };

      logger.info('JWT验证成功:', {
        doctor_id: decoded.doctor_id,
        username: decoded.username,
        role: decoded.role
      });

      next();
    });
  } catch (error) {
    logger.error('认证中间件发生错误:', error);
    return res.status(500).json({
      success: false,
      message: '认证过程发生错误',
      data: null
    });
  }
};

// 角色权限检查中间件
export const checkRole = (...allowedRoles) => {
  return (req, res, next) => {
    if (!req.user) {
      return res.status(401).json({
        success: false,
        message: '用户未认证',
        data: null
      });
    }

    if (!allowedRoles.includes(req.user.role)) {
      logger.warn('权限不足:', {
        doctor_id: req.user.doctor_id,
        username: req.user.username,
        role: req.user.role,
        requiredRoles: allowedRoles
      });

      return res.status(403).json({
        success: false,
        message: '权限不足',
        data: null
      });
    }

    next();
  };
};

// 可选认证中间件（不强制要求登录）
export const optionalAuth = (req, res, next) => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];

  if (token) {
    // P0-A安全修复：硬编码JWT密钥确保一致性
    const JWT_SECRET = 'endo_sight_uc_jwt_secret_key_2024_secure_token_generation_minimum_32_chars';

    // 启动时安全检查：JWT密钥必须存在
    if (!JWT_SECRET) {
      console.error('🚨 FATAL ERROR: JWT_SECRET is not defined.');
      console.error('🚨 Server cannot start for security reasons.');
      process.exit(1);
    }
    jwt.verify(token, JWT_SECRET, (err, decoded) => {
      if (!err) {
        req.user = {
          doctor_id: decoded.doctor_id,
          username: decoded.username,
          role: decoded.role,
          real_name: decoded.real_name
        };
      }
    });
  }

  next();
};